/*
 * Created by Weiting on 2011/11/18
 * copyright 2011 III. All rights reserved.
 *
 */
package com.eslserver.action.group;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.dao.GroupDAO;
import com.eslserver.to.Group;
import com.eslserver.to.wrapper.ESLCollectionPageWrapper;
import com.eslserver.to.wrapper.GroupWrapper;
import com.eslserver.util.DataTablesParamUtility;
import com.eslserver.util.JQueryDataTableParamModel;
import com.eslserver.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class LoadAllGroups extends HttpServlet {
	public static final Logger LOG = LoggerFactory
			.getLogger(LoadAllGroups.class);

	@SuppressWarnings("rawtypes")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		JQueryDataTableParamModel param = DataTablesParamUtility.getParam(req);
		String[] aColumns = { "esl_group_id", "esl_group_id", "name",
				"description" };

		String sLimit = null;
		String sOrder = null;
		String sWhere = null;
		String sQuery = null;
		String aQuery = null;

		int sEcho = 0;

		PrintWriter writer = resp.getWriter();

		int colLength = aColumns.length;
		if (param != null) {
			sEcho = param.sEcho;
		}

		// paging
		if (param != null && param.iDisplayStart != -1
				&& param.iDisplayLength != -1) {
			sLimit = " LIMIT " + param.iDisplayStart + ","
					+ param.iDisplayLength;
		}

		sOrder = "ORDER BY ";

		if (param == null || param.iSortColumnIndex == 0) {
			// default order by modify_date, col_index=0
			sOrder += "esl_group_id desc ";
		} else {
			// sorting by columns,starting from col_index=1
			sOrder += aColumns[param.iSortColumnIndex] + " "
					+ param.sSortDirection;
		}

		if (sOrder == "ORDERBY") {
			sOrder = null;
		}

		// filtering
		sWhere = "WHERE(";
		if (param != null && param.sSearch != null) {
			sWhere = "WHERE (";
			for (int i = 0; i < colLength; i++) {
				sWhere += aColumns[i] + " LIKE '%" + param.sSearch + "%' OR ";
			}
			sWhere = sWhere.substring(0, sWhere.length() - 3);
			sWhere += ") AND ";
		}

		sWhere += "isDelete=false ";

		/*
		 * SQL Queries Get data to display
		 */
		String selectedCols = "*"; // arrayToString(aColumns, ",");
		sQuery = "SELECT " + selectedCols + " FROM esl_group ";
		aQuery = "SELECT COUNT(" + selectedCols + ") FROM esl_group ";

		if (sWhere != null) {
			sQuery += sWhere;
			aQuery += sWhere;
		}
		if (sOrder != null) {
			sQuery += sOrder;
			aQuery += sOrder;
		}
		if (sLimit != null) {
			sQuery += sLimit;
		}

		try {
			GroupDAO groupDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getGroupDAO();
			ESLCollectionPageWrapper<Group> eslCollectionPageWrapper = groupDAO
					.loadGroupByPageQuery(sQuery, aQuery);

			Collection<ArrayList> returnCollection = new ArrayList<ArrayList>();

			for (Group group : eslCollectionPageWrapper.getESLCollection()) {
				ArrayList<String> groupInfo = new ArrayList<String>();
				GroupWrapper groupWrapper = GroupWrapper
						.createGroupWrapper(group);

				groupInfo.add("");
				groupInfo.add(groupWrapper.getGroup().getGroupID().toString());
				groupInfo.add(groupWrapper.getGroup().getName());
				groupInfo.add(groupWrapper.getESLCount().toString());
				groupInfo.add(groupWrapper.getGroup().getDescription());
				returnCollection.add(groupInfo);
			}

			Map<String, Object> output = new HashMap<String, Object>();
			output.put("sEcho", sEcho);
			output.put("iTotalRecords", eslCollectionPageWrapper.getTotal());
			output.put("iTotalDisplayRecords",
					eslCollectionPageWrapper.getFilteredTotal());
			output.put("aaData", returnCollection);
			writer.println(JSONResponseUtil.getJSONObjectString(output));

		} catch (DAOException e) {
			LOG.error("error laoding ESL", e);
		}
	}

}
